<?php

namespace app\mini\controller;
use app\admin\model\ShopModel;
use app\crm\model\OrderStatistics;
use app\crm\model\ReserveandLost;
use think\facade\Db;

class DataStatistics extends Access
{
    /**
     * 业绩页面
     *
     * @return void
     */
    public function readAdminShopAchievementStatistics()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $startMonthTime = strtotime(date('Y-m',$startTime));

        $endMonthTime = strtotime(date('Y-m',$endTime));
        if($request['type'] == 1)
        {
            //门店当月任务

            $task =Db::name('shop_task')

                ->where('month','>=',$startMonthTime)

                ->where('month','<=',$endMonthTime)

                ->group('shop_id')->column('sum(price) as price','shop_id');

        }else{
            //门店当月市场任务

            $task =Db::name('shop_task')

                ->where('month','>=',$startMonthTime)

                ->where('month','<=',$endMonthTime)

                ->group('market_id')->column('sum(price) as price','market_id');
        }
        print_r($task);exit;
    }

    /**
     *
     * 获取进店数据
     *
     * @return \think\response\Json
     */
    public function OrderDetails()
    {

        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $list = [];
        $rate = [];
        if($request['type'] == 1){
            $shopList = Db::name('shop')->field('shop_id,shop_name')->where([
                ['status','=',1]
            ])->select()->toArray();
            //网络进店
            $internet=Db::name('customer')->where([ ['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id', 'not in', [46,47,48,49,583]]])->group('shop_id')->column('count(id) as sum','shop_id');

            //转介绍
            $transfer_introduction=Db::name('customer')->where([['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id' ,'=', '49']])->group('shop_id')->column('count(id) as sum','shop_id');


            //外联  店转不计算门店进店统计
            $outreach=Db::name('customer')->where([['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id', 'in', [46,47,48,608]]])->group('shop_id')->column('count(id) as sum','shop_id');
            foreach ($shopList as $key => $value)
            {
                $temp = [
                    'shop_id'=>$value['shop_id'],
                    'name'=>$value['shop_name']??"",
                    'internet'=>$internet[$value['shop_id']]??0,
                    'transfer'=>$transfer_introduction[$value['shop_id']]??0,
                    'outreach'=>$outreach[$value['shop_id']]??0,
                ];
                $temp['sum'] = $temp['internet']+$temp['transfer']+$temp['outreach'];
                array_push($list,$temp);
            }
        }else{
            $marketList = Db::name('shop')->field('market_id,market_name')->where([
                ['status','=',1]
            ])->group('market_id')->select()->toArray();

            //网络进店
            $internet=Db::name('customer')->alias('a')->join('shop b','b.shop_id = a.shop_id','left')
                ->where([ ['a.first_time|a.second_time', 'between', "$startTime,$endTime"], ['a.source_id', 'not in', [46,47,48,49,583]]])->group('b.market_id')->column('count(a.id) as sum','b.market_id');

            //转介绍
            $transfer_introduction=Db::name('customer')->alias('a')->join('shop b','b.shop_id = a.shop_id','left')
                ->where([['a.first_time|a.second_time', 'between', "$startTime,$endTime"], ['a.source_id' ,'=', '49']])->group('b.market_id')->column('count(a.id) as sum','b.market_id');

            //外联  店转不计算门店进店统计
            $outreach=Db::name('customer')->alias('a')->join('shop b','b.shop_id = a.shop_id','left')
                ->where([['a.first_time|a.second_time', 'between', "$startTime,$endTime"], ['a.source_id', 'in', [46,47,48,608]]])->group('b.market_id')->column('count(a.id) as sum','b.market_id');

            foreach ($marketList as $key => $value)
            {
                $temp = [
                    'shop_id'=>$value['market_id'],
                    'name'=>$value['market_name']??"",
                    'internet'=>$internet[$value['market_id']]??0,
                    'transfer'=>$transfer_introduction[$value['market_id']]??0,
                    'outreach'=>$outreach[$value['market_id']]??0,
                ];
                $temp['sum'] = $temp['internet']+$temp['transfer']+$temp['outreach'];
                array_push($list,$temp);
            }
        }
        $internetSum = array_sum(array_column($list,'internet'));
        $rateData = Db::name('customer')->alias('a')
            ->join('setting b','b.id = a.source_id','left')
            ->where([
                ['a.source_id','in',[46,47,48,49]],
                ['a.first_time|a.second_time', 'between', "$startTime,$endTime"],
            ])
            ->group('a.source_id')
            ->field('count(a.id) as sum,b.name')
            ->select()->toArray();
        $sum = array_sum(array_column($rateData,'sum'))+$internetSum;
        foreach ($rateData as $value)
        {
            array_push($rate,[
                'name'=>$value['name'],
                'sum'=>$value['sum'],
                'rate'=>$sum>0?bcdiv($value['sum']*100,$sum,0):0
            ]);
        }

        array_push($rate,[
            'name'=>"网络进店",
            'sum'=>$internetSum,
            'rate'=>$sum>0?bcdiv($internetSum*100,$sum, 0):0
        ]);
        return $this->success(['list'=>$list,'pie'=>$rate],'获取完成');
    }

    /**
     *
     * 客户数据一级页面
     *
     * @return \think\response\Json
     */
    public function getCustomerData()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$startTime)));// 新单成交  开始时间

        $old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间

        $today = date('Y-m-d',time());

        $model = new ReserveandLost();

        $shopModel = new ShopModel();

        $shop_where = [];

        array_push($shop_where,['shop_type','=','2']);

        array_push($shop_where,['type','<>','2']);

        array_push($shop_where,['status','=','1']);

        $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

        $cj_customerIds = $model->cj_customer($shopIds,[]);

        $ls_customerIds = $model->lost_customer($cj_customerIds,$today); // 流失顾客

        $by_customerIds = $model->baoyou_customer($cj_customerIds,$today); // 保有顾客

        $by_rate = count($cj_customerIds)>0 ? bcmul(bcdiv(count($by_customerIds),count($cj_customerIds),4),100,2).'%' : '0%';  //保有率

        $classification = [
            71=>"C",
            72=>"B",
            73=>"A",
        ];
        $level = [
            1=>"purple",
            2=>"white",
            3=>"gold"
        ];
        $levelCount = Db::name('customer')->where([
            ['member_classification','in',[71,72,73]]
        ])->field('count(id) as sum,member_classification')->group('member_classification')->select()->toArray();
        $membership_leve = Db::name('customer')->where([
            ['membership_leve','<>',0]
        ])->field('count(id) as sum,membership_leve')->group('membership_leve')->select()->toArray();

        $scarList = Db::name('customer')
            ->alias('b')
            ->where('b.cj_time','>=',$old_start_time)//2022.01.01
            ->where('b.cj_time','<=',$old_end_time) //2022.01.31
            ->where('b.cj_money','>',0)
            ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
            ->where('sp.business_type','=',1)
            ->where('sp.type','=',3)
            ->column('b.id,b.shop_id,b.cj_money,telephone');

        $bahenNum =$shopModel->redAdminProjectByShopId($scarList,$old_start_time,$old_end_time,$endTime);

        $xiangmNum =$shopModel->redAdminXmByShopId($scarList,$old_start_time,$old_end_time,$endTime);

        $gxmanyiNum =$shopModel->setGXmanyiCustomerShopList($scarList,$old_start_time,$old_end_time,$endTime);


        $developRate =count($scarList)>0 ? (bcdiv($bahenNum,count($scarList),4)*100).'%' :'0%';  //疤痘二次消费率
        $popularityRate =count($scarList)>0 ? (bcdiv($xiangmNum,count($scarList),4)*100).'%' :'0%'; //项目普及率
        $gongxiaomanyi =count($scarList)>0 ? (bcdiv($gxmanyiNum,count($scarList),4)*100).'%' :'0%'; //功效满意度

        $data = [
            'ls_customerIds'=>count($ls_customerIds),
            'by_customerIds'=>count($by_customerIds),
            'by_rate'=>$by_rate,
            'developRate'=>$developRate,
            'popularityRate'=>$popularityRate,
            'gongxiaomanyi'=>$gongxiaomanyi,
        ];
        foreach ($levelCount as $value)
        {
            $data[$classification[$value['member_classification']]]=$value['sum'];
        }
        foreach ($membership_leve as $value)
        {
            $data[$level[$value['membership_leve']]]=$value['sum'];
        }
        return $this->success($data,"获取完成");

    }

    /**
     * 保留、流失、保有率
     *
     * @return \think\response\Json
     */
    public function getCustomerStatus()
    {
        $request = $this->request->param();

        $today = date('Y-m-d',time());

        $model = new ReserveandLost();

        $shopModel = new ShopModel();

        $shop_where = [];

        array_push($shop_where,['shop_type','=','2']);

        array_push($shop_where,['type','<>','2']);

        array_push($shop_where,['status','=','1']);

        $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

        $cj_customerIds = $model->cj_customer($shopIds,[]);

        $ls_customerIdsCount = $model->shop_lost_customer($cj_customerIds,$today); // 流失顾客

        $by_customerIdsCount = $model->shop_baoyou_customer($cj_customerIds,$today); // 保有顾客

        $shops = Db::name('shop')->where($shop_where)->column('shop_name,market_id,market_name','shop_id');
        foreach ($ls_customerIdsCount as $value)
        {
            $shops[$value['shop_id']]['liushi'] = $value['sum']??0;
        }
        foreach ($by_customerIdsCount as $value)
        {
            $shops[$value['shop_id']]['baoyou'] = $value['sum']??0;
        }

        if($request['type'] == 1)//门店
        {
            foreach ($shops as $key => $value)
            {
                if(empty($value['liushi']))
                {
                    $shops[$key]['liushi']=0;
                    $value['liushi'] = 0;
                }
                if(empty($value['baoyou']))
                {
                    $shops[$key]['baoyou']=0;
                    $value['baoyou'] = 0;
                }
                $shops[$key]['by_rate'] = $value['baoyou']>0 ? bcmul(bcdiv($value['liushi'],$value['baoyou'],4),100,2).'%' : '0%';  //保有率
            }
            $shops = array_merge($shops,[]);
            return $this->success($shops,"获取完成",count($shops));
        }else{
            $market = [];
            foreach ($shops as $key=> $value)
            {
                if(empty($market[$value['market_id']]))
                {
                    $market[$value['market_id']]=[
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                        'liushi'=>$value['liushi']??0,
                        'baoyou'=>$value['baoyou']??0,
                    ];
                }else{
                    $market[$value['market_id']]['liushi']+=$value['liushi']??0;
                    $market[$value['market_id']]['baoyou']+=$value['baoyou']??0;

                }
                foreach ($market as $key => $value)
                {
                    if(empty($value['liushi']))
                    {
                        $market[$key]['liushi']=0;
                        $value['liushi'] = 0;
                    }
                    if(empty($value['baoyou']))
                    {
                        $market[$key]['baoyou']=0;
                        $value['baoyou'] = 0;
                    }
                    $market[$key]['by_rate'] = $value['baoyou']>0 ? bcmul(bcdiv($value['liushi'],$value['baoyou'],4),100,2).'%' : '0%';  //保有率
                }
            }
            return $this->success($market,"获取完成",count($market));

        }

//        $by_rate = count($cj_customerIds)>0 ? bcmul(bcdiv($ls_customerIdsCount,$by_customerIdsCount,4),100,2).'%' : '0%';  //保有率
    }

    /**
     * 客户数据-客户分类二级页面
     * @return \think\response\Json
     */
    public function getCustomerType()
    {
        $request = $this->request->param();


        $classification = [
            71=>"C",
            72=>"B",
            73=>"A",
        ];//分类id
        if($request['type'] == 1)//门店
        {
            $levelCount = Db::name('customer')->alias('a')
                ->join('shop b','b.shop_id = a.shop_id','left')
                ->where([
                    ['a.member_classification','in',[71,72,73]]
            ])->field('count(a.id) as sum,a.member_classification,b.shop_id,b.shop_name')->group('a.member_classification,a.shop_id')->select()->toArray();
            foreach ($levelCount as $value)
            {
                if(empty($data[$value['shop_id']]))
                {
                    $data[$value['shop_id']] = [
                        'shop_id'=>$value['shop_id'],
                        'shop_name'=>$value['shop_name'],
                    ];
                }
                $data[$value['shop_id']][$classification[$value['member_classification']]]=$value['sum'];

            }
        }else{//市场
            $levelCount = Db::name('customer')->alias('a')
                ->join('shop b','b.shop_id = a.shop_id','left')
                ->where([
                    ['a.member_classification','in',[71,72,73]]
                ])->field('count(a.id) as sum,a.member_classification,b.market_id,b.market_name')->group('a.member_classification,b.market_id')->select()->toArray();
            foreach ($levelCount as $value)
            {
                if(empty($data[$value['market_id']]))
                {
                    $data[$value['market_id']] = [
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                    ];
                }
                $data[$value['market_id']][$classification[$value['member_classification']]]=$value['sum'];

            }
        }
//        foreach ($levelCount as $key => $value)
//        {
//            $levelCount[$key]['name']=$classification[$value['member_classification']]??"";
//        }
        $data = array_merge($data,[]);
        return $this->success($data,"获取完成",count($data));
    }

    /**
     * 客户数据-会员数据
     *
     * @return \think\response\Json
     */
    public function getMemberCustomer()
    {
        $request = $this->request->param();

        $level = [
            1=>"purple",
            2=>"white",
            3=>"gold"
        ];
        $data = [];
        if($request['type'] == 1)//门店
        {
            $membership_leve = Db::name('customer')->alias('a')
                ->join('shop b','b.shop_id = a.shop_id')
                ->where([
                    ['a.membership_leve','<>',0]
                ])
                ->field('count(a.id) as sum,a.membership_leve,b.shop_id,b.shop_name')->group('a.membership_leve,b.shop_id')->select()->toArray();
            foreach ($membership_leve as $value)
            {
                if(empty($data[$value['shop_id']]))
                {
                    $data[$value['shop_id']] = [
                        'shop_id'=>$value['shop_id'],
                        'shop_name'=>$value['shop_name'],
                    ];
                }
                $data[$value['shop_id']][$level[$value['membership_leve']]]=$value['sum'];

            }
        }else{
            $membership_leve = Db::name('customer')->alias('a')
                ->join('shop b','b.shop_id = a.shop_id')
                ->where([
                    ['a.membership_leve','<>',0]
                ])
                ->field('count(a.id) as sum,a.membership_leve,b.market_id,b.market_name')->group('a.membership_leve,b.market_id')->select()->toArray();
            foreach ($membership_leve as $value)
            {
                if(empty($data[$value['market_id']]))
                {
                    $data[$value['market_id']] = [
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                    ];
                }
                $data[$value['market_id']][$level[$value['membership_leve']]]=$value['sum'];

            }
        }
        $data = array_merge($data,[]);
        return $this->success($data,"获取完成",count($data));


    }
    public function getServiceData()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$startTime)));// 新单成交  开始时间

        $old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间

        $shopModel = new ShopModel();
        $shop_where = [];

//        array_push($shop_where,['shop_type','=','2']);

//        array_push($shop_where,['type','<>','2']);

        array_push($shop_where,['status','=','1']);
        if($request['type'] == 1)//门店
        {
            $list = Db::name('shop')->where($shop_where)->column('shop_id,shop_name');
            foreach ($list as $key => $value)
            {
                $scarList = Db::name('customer')
                    ->alias('b')
                    ->where('b.cj_time','>=',$old_start_time)//2022.01.01
                    ->where('b.cj_time','<=',$old_end_time) //2022.01.31
                    ->where('b.cj_money','>',0)
                    ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
                    ->where('sp.business_type','=',1)
                    ->where('sp.type','=',3)
                    ->where('sp.shop_id','=',$value['shop_id'])
                    ->column('b.id,b.shop_id,b.cj_money,telephone');

                $bahenNum =$shopModel->redAdminProjectByShopId($scarList,$old_start_time,$old_end_time,$endTime);

                $xiangmNum =$shopModel->redAdminXmByShopId($scarList,$old_start_time,$old_end_time,$endTime);

                $gxmanyiNum =$shopModel->setGXmanyiCustomerShopList($scarList,$old_start_time,$old_end_time,$endTime);

                $list[$key]['developRate'] =count($scarList)>0 ? (bcdiv($bahenNum,count($scarList),4)*100).'%' :'0%';  //疤痘二次消费率
                $list[$key]['popularityRate'] =count($scarList)>0 ? (bcdiv($xiangmNum,count($scarList),4)*100).'%' :'0%'; //项目普及率
                $list[$key]['gongxiaomanyi'] =count($scarList)>0 ? (bcdiv($gxmanyiNum,count($scarList),4)*100).'%' :'0%'; //功效满意度
            }
        }else{
            $list = Db::name('shop')->where($shop_where)->column('market_id,market_name');
            foreach ($list as $key => $value)
            {
                $scarList = Db::name('customer')
                    ->alias('b')
                    ->where('b.cj_time','>=',$old_start_time)//2022.01.01
                    ->where('b.cj_time','<=',$old_end_time) //2022.01.31
                    ->where('b.cj_money','>',0)
                    ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
                    ->where('sp.business_type','=',1)
                    ->where('sp.type','=',3)
                    ->where('sp.market_id','=',$value['market_id'])
                    ->column('b.id,b.shop_id,b.cj_money,telephone');

                $bahenNum =$shopModel->redAdminProjectByShopId($scarList,$old_start_time,$old_end_time,$endTime);

                $xiangmNum =$shopModel->redAdminXmByShopId($scarList,$old_start_time,$old_end_time,$endTime);

                $gxmanyiNum =$shopModel->setGXmanyiCustomerShopList($scarList,$old_start_time,$old_end_time,$endTime);

                $list[$key]['developRate'] =count($scarList)>0 ? (bcdiv($bahenNum,count($scarList),4)*100).'%' :'0%';  //疤痘二次消费率
                $list[$key]['popularityRate'] =count($scarList)>0 ? (bcdiv($xiangmNum,count($scarList),4)*100).'%' :'0%'; //项目普及率
                $list[$key]['gongxiaomanyi'] =count($scarList)>0 ? (bcdiv($gxmanyiNum,count($scarList),4)*100).'%' :'0%'; //功效满意度
            }
        }
        return $this->success($list,"获取完成",count($list));
    }

    /**
     * 进店
     *
     * @return \think\response\Json|void
     */
    public function getComeInData()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $orderStatistics = new OrderStatistics();

        $where = [
//                ['a.shop_id', 'in', $shop_id],
            ['a.cj_time', 'between', "$startTime,$endTime"],
            ['a.cj_money', '>=', 500]
        ];
        if(!empty($request['market_id']))
        {
            array_push($where,['b.market_id','=',$request['market_id']]);

        }
        $receive_deal=Db::name('customer')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->where($where)
            ->field('count(DISTINCT(a.id)) as sum,a.shop_id,b.shop_name,b.market_id,b.market_name,b.shop_type')
            ->group('a.shop_id')->select()->toArray();
        foreach ($receive_deal as $key => $value)
        {
            $receive_deal[$key]['receive_deal'] = isset($receive_deal[$key]) ? $receive_deal[$key]['sum'] : 0;//成交个数
            if($receive_deal[$key]['market_id'] == 8 || $receive_deal[$key]['market_id'] == 9 || $receive_deal[$key]['market_id'] == 10|| $receive_deal[$key]['market_id'] == 11)
            {
                $receive_deal[$key]['new_total'] = $orderStatistics->sumShopPayMoneyNewMZ('XD',$receive_deal[$key]['shop_id'],$receive_deal[$key]['shop_type'],$startTime,$endTime);
//                    $budanMoney = $this->sumShopPayMoneyNewMZ('BD',$receive_deal[$key]['shop_id'],$receive_deal[$key]['shop_type'],$startTime,$endTime);

            }else{
                $receive_deal[$key]['new_total'] = $orderStatistics->sumShopPayMoneyNew('XD',$receive_deal[$key]['shop_id'],$receive_deal[$key]['shop_type'],$startTime,$endTime);
//                    $budanMoney = $this->sumShopPayMoneyNew('BD',$receive_deal[$key]['shop_id'],$receive_deal[$key]['shop_type'],$startTime,$endTime);
            }
            $receive_deal[$key]['sheet_money'] = bcdiv($receive_deal[$key]['new_total'],$receive_deal[$key]['receive_deal'],2);//均单值



            $internet=Db::name('customer')->where([['shop_id', '=', $value['shop_id']], ['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id', 'not in', [46,47,48,49,583]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();


            $internet=array_column($internet,null,'shop_id');


            //转介绍


            $transfer_introduction=Db::name('customer')->where([['shop_id', '=', $value['shop_id']], ['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id' ,'=', '49']])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();


            $transfer_introduction=array_column($transfer_introduction,null,'shop_id');


            //外联  店转不计算门店进店统计


            $outreach=Db::name('customer')->where([['shop_id', '=', $value['shop_id']], ['first_time|second_time', 'between', "$startTime,$endTime"], ['source_id', 'in', [46,47,48,608]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();


            $outreach=array_column($outreach,null,'shop_id');


            //线上导客数量


            $internet_total=Db::name('customer')->where([['shop_id', '=', $value['shop_id']], ['create_time', 'between', "$startTime,$endTime"], ['source_id', 'not in', [46,47,48,49]]])->field('count(id) as sum,shop_id')->group('shop_id')->select()->toArray();


//            print_r($internet);
//            print_r($transfer_introduction);
//            print_r($outreach);exit;

            $internet_num  = isset($internet[$value['shop_id']]) ? $internet[$value['shop_id']]['sum'] : 0;//进店数量


            $introduction_num = isset($transfer_introduction[$value['shop_id']]) ? $transfer_introduction[$value['shop_id']]['sum'] : 0;//转介绍数量


            $outreach_num  = isset($outreach[$value['shop_id']]) ? $outreach[$value['shop_id']]['sum'] : 0;//门店外联数量


            $receive_deal[$key]['enter_total_num'] = bcadd($internet_num, bcadd($outreach_num, $introduction_num, 0), 0);//进店数量合计

            if ($receive_deal[$key]['enter_total_num'])
            {
                $receive_deal[$key]['turnover_rate'] = (bcdiv($receive_deal[$key]['receive_deal'],$receive_deal[$key]['enter_total_num'],4)*100).'%';//成交率
            }else{
                $receive_deal[$key]['turnover_rate'] =  '';//成交率
            }

        }

        if($request['type'] == 1)//门店
        {
            $receive_deal = array_merge($receive_deal,[]);
            return $this->success($receive_deal,"获取完成",count($receive_deal));
        }else {
            $data = [];
            foreach ($receive_deal as $key => $value)
            {
                if(empty($data[$key]))
                {
                    $data[$key]=[
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                        'receive_deal'=>$value['receive_deal'],
                        'enter_total_num'=>$value['enter_total_num'],
                        'new_total'=>$value['new_total']
                    ];
                    $data[$key]['sheet_money']=$value['receive_deal']?bcdiv($value['new_total'],$value['receive_deal'],2):0;
                    $data[$key]['turnover_rate']=$value['enter_total_num']?(bcdiv($value['receive_deal'],$value['enter_total_num'],4)*100).'%':'';
                }
            }
            return $this->success($data,"获取完成",count($data));
        }

    }

    /**
     * 获取体验成交
     *
     * @return \think\response\Json
     */
    public function getExperienceDeal()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;


        $shop_where = [];

//        array_push($shop_where,['shop_type','=','2']);
//
//        array_push($shop_where,['type','<>','2']);

        array_push($shop_where,['status','=','1']);

        if(!empty($request['market_id']))//二级页面
        {
            array_push($shop_where,['market_id','=',$request['market_id']]);

        }


        $shops = Db::name('shop')->where($shop_where)->column('shop_id,shop_name,market_id,market_name','shop_id');

        $experience_good = [150,168,165];
        //查询销售出库单中的是否体验个数---2022.04.11 修改

        $experience_total=Db::name('service_log')->where([['create_time', 'between', [$startTime,$endTime]], ['goods_id', 'in', $experience_good]])->field('count(customer_id) as sum,shop_id')->group('shop_id')->select()->toArray();

        $experience_total=array_column($experience_total,null,'shop_id');


        //体验成交个数 收款单中 1是体验单，2是成交的金额需要大于500以上的新单人数统计,3不算收款调整


        $experience_deal=Db::name('shop_refund_order')->where([ ['deal_time', 'between', "$startTime,$endTime"],['is_experience', '=', 1],['status', '=', 2],['type', '=', 3],['order_type', '=', 1],['pay_amount', '>', 500],['refund_type', '<>', '101.03']])->field('count(DISTINCT(uid)) as sum,shop_id')->group('shop_id')->select()->toArray();


        $experience_deal=array_column($experience_deal,null,'shop_id');

        foreach ($shops as $key => $value)
        {
            $shops[$key]['experience_total'] = $experience_total[$key]['sum']??0;
            $shops[$key]['experience_deal'] = $experience_deal[$key]['sum']??0;
            $shops[$key]['experience_rate'] = $shops[$key]['experience_total']?(bcdiv($shops[$key]['experience_deal'],$shops[$key]['experience_total'],4)*100).'%':'';
        }
        if($request['type'] == 1)//门店
        {
            $shops = array_merge($shops,[]);
            return $this->success($shops,"获取完成",count($shops));
        }else {
            $data = [];
            foreach ($shops as $key => $value)
            {
                if(empty($data[$key]))
                {
                    $data[$key]=[
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                        'experience_total'=>$value['experience_total'],
                        'experience_deal'=>$value['experience_deal']
                    ];
                    $data[$key]['experience_rate']=$value['experience_total']?(bcdiv($value['experience_deal'],$value['experience_total'],4)*100).'%':'';
                }
            }
            return $this->success($data,"获取完成",count($data));
        }
    }
    public function getOrderTypeDealRate()
    {
        $request = $this->request->param();

        $startTime =$request['start_time'] ?? 0;

        $endTime =$request['end_time'] ?? 0;

        $startTime = strtotime($startTime);

        $endTime = strtotime($endTime)+86399;

        $shop_where = [];

        array_push($shop_where,['status','=','1']);

        if(!empty($request['market_id']))//二级页面
        {
            array_push($shop_where,['market_id','=',$request['market_id']]);

        }
        $shops = Db::name('shop')->where($shop_where)->column('shop_id,shop_name,market_id,market_name','shop_id');


        $where = [];
        if(!empty($request['market_id']))//二级页面
        {
            array_push($where,['b.market_id','=',$request['market_id']]);

        }
        array_push($where,['a.deal_time','between',[$startTime,$endTime]]);
//        array_push($where,['a.extra_type','!=',1]);
        array_push($where,['a.type','=',3]);
        array_push($where,['a.status','=',2]);

        $refund = Db::name('shop_refund_order')->alias('a')//非痘痘
            ->join('shop b','a.shop_id = b.shop_id','left')
            ->where($where)->where('a.extra_type','<>',1)->field('b.shop_id,b.shop_name,b.market_id,b.market_name,a.business_type,a.extra_type,count(a.id) as sum')->group('a.shop_id,a.business_type')->select()->toArray();
        $refund2 = Db::name('shop_refund_order')->alias('a')
            ->join('shop b','a.shop_id = b.shop_id','left')//痘痘
            ->where($where)->where([['a.extra_type','=',1],['a.business_type','=',1]])->field('b.shop_id,b.shop_name,b.market_id,b.market_name,a.business_type,a.extra_type,count(a.id) as sum')->group('a.shop_id,a.business_type')->select()->toArray();
        $refund = array_merge($refund,$refund2);
//        $refund = array_column($refund,null,'shop_id');
        foreach ($refund as $value)
        {
//            $shops[$value['shop_id']]['bh']=$value['sum'];
            if($value['business_type']==2)
            {
                $shops[$value['shop_id']]['xm']=$value['sum']??0;
            }
            if($value['business_type']==1&&$value['extra_type']==0)
            {
                $shops[$value['shop_id']]['bh']=$value['sum']??0;
            }
            if($value['business_type']==1&&$value['extra_type']==1)
            {
                $shops[$value['shop_id']]['dd']=$value['sum']??0;
            }
        }
        foreach ($shops as $key =>$value)
        {
            if(empty($value['xm']))
            {
                $shops[$key]['xm']=0;
            }
            if(empty($value['bh']))
            {
                $shops[$key]['bh']=0;
            }
            if(empty($value['dd']))
            {
                $shops[$key]['dd']=0;
            }
            $shops[$key]['sum']=$shops[$key]['xm']+$shops[$key]['bh']+$shops[$key]['dd'];
            $shops[$key]['xm_rate'] = $shops[$key]['sum']>0?(bcdiv($shops[$key]['xm'],$shops[$key]['sum'],4)*100).'%':'';
            $shops[$key]['bh_rate'] = $shops[$key]['sum']>0?(bcdiv($shops[$key]['bh'],$shops[$key]['sum'],4)*100).'%':'';
            $shops[$key]['dd_rate'] = $shops[$key]['sum']>0?(bcdiv($shops[$key]['dd'],$shops[$key]['sum'],4)*100).'%':'';

        }
        if($request['type'] == 1)//门店
        {
            $shops = array_merge($shops,[]);
            return $this->success($shops,"获取完成",count($shops));
        }else {
            $data = [];
            foreach ($shops as $key => $value)
            {
                if(empty($data[$key]))
                {
                    $data[$key]=[
                        'market_id'=>$value['market_id'],
                        'market_name'=>$value['market_name'],
                        'xm'=>$value['xm'],
                        'bh'=>$value['bh'],
                        'dd'=>$value['dd'],
                        'sum'=>$value['xm']+$value['bh']+$value['dd']
                    ];
                    $data[$key]['xm_rate'] = $data[$key]['sum']>0?(bcdiv($data[$key]['xm'],$data[$key]['sum'],4)*100).'%':'';
                    $data[$key]['bh_rate'] = $data[$key]['sum']>0?(bcdiv($data[$key]['bh'],$data[$key]['sum'],4)*100).'%':'';
                    $data[$key]['dd_rate'] = $data[$key]['sum']>0?(bcdiv($data[$key]['dd'],$data[$key]['sum'],4)*100).'%':'';
                }
            }
            return $this->success($data,"获取完成",count($data));
        }
    }
}


